import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import math

data = np.loadtxt(r'../data/coffee.txt', delimiter=',')
x = data[:, :-1]
y = data[:, -1]

# C: 松弛因子的惩罚项，C越大松弛因子越小
# kernel: 核函数（linear, rbf, poly, sigmoid）
# gamma: rbf的参数，为 1/sigma
svc = SVC(C=1, kernel='rbf', gamma=50)
svc.fit(x, y)
print(f'model accuracy = {svc.score(x, y)}')
print(f'support vector n = {svc.n_support_}')
print(f'support vector index = {svc.support_}')
print(f'support vector array = {svc.support_vectors_}')
print(f'prediction = {svc.predict(x)}')
print(f'distant from sv to plane = {svc.decision_function(x)}')

x1_min, x1_max = np.min(x[:, 0]), np.max(x[:, 0])
x2_min, x2_max = np.min(x[:, 1]), np.max(x[:, 1])
xx, yy = np.mgrid[x1_min:x1_max:300j, x2_min:x2_max:300j]
xy = np.c_[xx.ravel(), yy.ravel()]
z = svc.decision_function(xy).reshape(xx.shape)
z11 = svc.predict(xy).reshape(xx.shape)
plt.contourf(xx, yy, z11, cmap=plt.cm.Paired)
plt.contour(xx, yy, z, colors=['w', 'r', 'g'], linestyles=['-'], levels=[-0.3, 0, 0.3])
plt.scatter(x[:, 0], x[:, 1], c=y)
plt.show()
